package top.ajunnihao.core.spring.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO 统一异常处理
 *
 * @author AJun
 * @version 1.0.0
 * @date 2020/5/16
 */
@ControllerAdvice
public class ExceptionHandlerController {

    /**
     * 日志记录
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerController.class);

    /**
     * 异常处理:拦截所有异常
     *
     * @param req 请求对象
     * @param e   拦截到的异常
     * @return ModelAndView
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandle(HttpServletRequest req, Exception e) throws Exception {
        LOGGER.error("Request URL : {}, Exception : {}", req.getRequestURL(), e.getMessage());

        /* 如果存在 @ResponseStatus 注解的异常，则跳转到指定状态码的页面 */
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url", req.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }

    /**
     * 异常处理:拦截404异常
     *
     * @param req 请求对象
     * @param e   拦截到的异常
     * @return ModelAndView
     */
    @ExceptionHandler(NotFoundException.class)
    public ModelAndView notFoundExceptionHandle(HttpServletRequest req, NotFoundException e) throws Exception {
        LOGGER.error("Request URL : {}, NotFoundException : {}", req.getRequestURL(), e.getMessage());

        ModelAndView mv = new ModelAndView();
        mv.addObject("code", e.getCode());
        mv.addObject("url", req.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/404");
        return mv;
    }

    /**
     * 异常处理:拦截500异常
     *
     * @param req 请求对象
     * @param e   拦截到的异常
     * @return ModelAndView
     */
    @ExceptionHandler(InternalServerException.class)
    public ModelAndView internalServerExceptionHandle(HttpServletRequest req, InternalServerException e) throws Exception {
        LOGGER.error("Request URL : {}, InternalServerException : {}", req.getRequestURL(), e.getMessage());

        ModelAndView mv = new ModelAndView();
        mv.addObject("code", e.getCode());
        mv.addObject("url", req.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/500");
        return mv;
    }

}
